//验证规则
const verifyParams = require("../verifyParams/user");
//数据库执行语句函数
const { sqlPromise } = require("../db/sqlPromise");
//引入生成token模块
const jwt = require('jsonwebtoken')
//引入密码加密模块
const bcrypt = require('bcryptjs')
// 登录
exports.login = async (ctx) => {
  ctx.verifyParams(verifyParams.login);  //输入验证
  let sql = "select * from sp_user where username=?";
  let results = await sqlPromise(sql, ctx.request.body.username);
  if (!results.length)
    return (ctx.body = {
      status: 404,
      msg: "用户不存在,请先注册",
    });
  //验证密码
  const compareRes = bcrypt.compareSync(ctx.request.body.password, results[0].password)
  if (!compareRes) {
    return ctx.body = {
      status: 403,
      message: "密码错误",
    }
  }
  let token = jwt.sign({ 'username': ctx.request.body.username }, 'xlq', { expiresIn: '10h' })
  ctx.body = {
    status: 200,
    msg: "登录成功",
    token: 'Bearer ' + token
  };
};
// 注册
exports.regUser = async (ctx) => {
  ctx.verifyParams(verifyParams.regUser);//输入验证
  // 查询用户名是否已被占用
  let sql = 'select * from sp_user where username=?'
  let results = await sqlPromise(sql, ctx.request.body.username)
  if (results.length > 0) return (ctx.body = {
    status: 404,
    msg: "注册失败 用户名已存在",
  });
  let serectPwd = bcrypt.hashSync(ctx.request.body.password, 10);
  let insertSql = 'insert into sp_user set ?'
  let { username: usernameA, password: password, email: user_email, mobile: user_tel } = ctx.request.body
  let data = {
    username: usernameA,
    password: serectPwd,
    user_email,
    user_tel,
    create_time: new Date()
  }
  await sqlPromise(insertSql, data)
  let dataSql = 'select * from sp_user where username=?'
  let [dataRes] = await sqlPromise(dataSql, data.username)
  ctx.body = {
    data: {
      id: dataRes.user_id,
      username: dataRes.username,
      mobile: dataRes.user_tel,
      openid: dataRes.qq_open_id,
      email: dataRes.user_email,
      create_time: dataRes.create_time,
      modify_time: dataRes.update_time,
      is_delete: Number(dataRes.is_delete),
      is_active: Number(dataRes.is_active),
    },
    meta: {
      msg: "用户创建成功",
      status: 200
    }
  };
};